package waylines.waypoints
{
	import org.flintparticles.twoD.particles.Particle2D;
	import org.flintparticles.common.particles.Particle;
	import org.flintparticles.common.emitters.Emitter;
	import org.flintparticles.common.actions.ActionBase;

	public class FollowWaypoints extends ActionBase
	{
		/**
		 * Whether the particles head for the first waypoint after passing through the last waypoint.
		 */
		public var loop:Boolean = false;
		/**
		 * Whether the particles' mass is taken into account. 
		 * If true, the acceleration applied to a particle is divided by the particle's mass.
		 */
		public var massless:Boolean = true;
		
		private var _waypoints:Array;
		
		public function FollowWaypoints(waypoints:Array = null, loop:Boolean = false, massless:Boolean = true)
		{
			_waypoints = waypoints;
			this.loop = loop;
			this.massless = massless;
		}
		override public function update(emitter:Emitter, particle:Particle, time:Number):void 
		{
			if (!_waypoints.length) return;
			
			var p2D:Particle2D = Particle2D(particle);
			if (!p2D.dictionary[FollowWaypoints])
			{
				 p2D.dictionary[FollowWaypoints] = 0;
			}
			
			var index:int = p2D.dictionary[FollowWaypoints];
			
			var waypoint:Waypoint = _waypoints[index] as Waypoint;
			var dx:Number = p2D.x - waypoint.x;
			var dy:Number = p2D.y - waypoint.y;
			if (dx * dx + dy * dy <= waypoint.radius * waypoint.radius) 
			{
				if (index < _waypoints.length - 1) 
				{
					p2D.dictionary[FollowWaypoints]++;
					waypoint = _waypoints[index + 1];
				} 
				else 
				{
					if (loop) waypoint = _waypoints[0];
					else return;
				}
				dx = p2D.x - waypoint.x;
				dy = p2D.y - waypoint.y;
			}
			
			var r:Vec2D = new Vec2D(dx, dy);//Vec2DPool.get(dx, dy);
			var len:Number = r.length;
			if (len < waypoint.epsilon) len = waypoint.epsilon;
			r.length = -waypoint.strength * Math.pow(len, -0.5 * waypoint.attenuationPower);
			if (!massless) r.length /= p2D.mass;
			//Vec2DPool.recycle(r);
			
			p2D.velX += r.x;
			p2D.velY += r.y;
		}
	}
}
